package com.bcx.wind.workflow.imp.cmd.repositorycmd.processconfigcmd;

import com.bcx.wind.workflow.entity.WindProcessConfig;
import com.bcx.wind.workflow.errorcontext.WindError;
import com.bcx.wind.workflow.interceptor.Command;
import com.bcx.wind.workflow.interceptor.CommandContext;
import com.bcx.wind.workflow.support.ObjectHelper;

import java.util.Map;

import static com.bcx.wind.workflow.message.ErrorCode.DATABASE_OPERATE_ERROR;
import static com.bcx.wind.workflow.message.ErrorCode.OPERATE_FAIL;
import static com.bcx.wind.workflow.message.ErrorCode.QUERY_EMPTY;

/**
 * 添加节点配置数据命令
 *
 * @author zhanglei
 */
public class AddNodeConfigCommand implements Command<Integer> {

    private static final String PROCESS_CONFIG = "processConfig";

    /**
     * 配置ID
     */
    private String configId;

    /**
     * 节点配置MAP数据
     */
    private Map<String,Object> nodeConfigMap;


    /**
     * 操作的配置数据
     */
    private WindProcessConfig windProcessConfig;

    /**
     * 执行数据
     */
    private CommandContext commandContext;

    public AddNodeConfigCommand(String configId, Map<String,Object> nodeConfigMap){
        this.configId = configId;
        this.nodeConfigMap = nodeConfigMap;
    }

    @Override
    public Integer executor(CommandContext context) {
        try{
            this.commandContext = context;
            return this.execute();
        }catch (Exception e){
            commandContext.log(e);
        }
        return null;
    }

    private Integer execute(){
        //校验
        checkArgs();
        //添加
        int ret = addNodeConfig();
        //更新缓存
        updateCache();
        return ret;
    }

    private void  updateCache(){
        this.commandContext.getConfiguration().addProcessConfigCache(this.windProcessConfig.getProcessId(),this.windProcessConfig);
    }

    /**
     * 添加节点配置操作
     * @return   添加结果
     */
    private int  addNodeConfig(){
        for(Map.Entry<String,Object> args : this.nodeConfigMap.entrySet()){
            String key = args.getKey();
            Object value = args.getValue();
            this.windProcessConfig.addNodeConfig(key,value);
        }
        int ret = this.commandContext.access().updateProcessConfig(this.windProcessConfig);
        if(ret != 1){
            WindError.error(DATABASE_OPERATE_ERROR,null);
        }
        return ret;
    }

    /**
     * 校验参数
     */
    private  void checkArgs(){
        if(this.configId == null){
            WindError.error(OPERATE_FAIL,null,PROCESS_CONFIG,"addNodeConfig","configId");
        }
        this.windProcessConfig = this.commandContext.access().getProcessConfigById(configId);
        if(this.windProcessConfig == null){
            WindError.error(QUERY_EMPTY,null,PROCESS_CONFIG,configId);
        }

        if(ObjectHelper.isEmpty(this.nodeConfigMap)){
            WindError.error(OPERATE_FAIL,null,PROCESS_CONFIG,"addNodeConfig","nodeConfig");
        }
    }
}
